package com.slkj.shilixiaoyuanapp.ui.teacher.tool.Purchase;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.google.gson.Gson;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.WplySqrandBmEntity;
import com.slkj.shilixiaoyuanapp.entity.code.ToolCode;
import com.slkj.shilixiaoyuanapp.entity.commitdata.PurchaseDetailedCommitData;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.common.CommonToolHistoryActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.reimbursement.ApplyReimbursementActivity;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.PickerViewProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;

@ActivityInfo(layout = R.layout.activity_purchase, title = "采购 ", rightHint = "历史记录")
public class ApplyPurchaseActivity extends BaseActivity {
    @BindView(R.id.tv_user_name)
    TextView tvUserName;

    @BindView(R.id.tv_menoy)
    TextView tvMenoy;
    @BindView(R.id.tv_now_day_time)
    TextView tvNowDayTime;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.layout_chose_type)
    RelativeLayout layoutChoseType;
    @BindView(R.id.edit_num)
    EditText editNum;
    @BindView(R.id.edit_price)
    EditText editPrice;
    @BindView(R.id.tv_bm)
    TextView tvBm;
    @BindView(R.id.layoout_bumen)
    RelativeLayout layooutBumen;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.layout_chose_time)
    RelativeLayout layoutChoseTime;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    @BindView(R.id.tv_spr)
    TextView tvSpr;
    private int bmTypeId = NO_CHOSE;
    List<Integer> sqrIds = new ArrayList<>();
    private ArrayList<PeopleEntity> peopleEntities = new ArrayList<>();
    private ArrayList<WplySqrandBmEntity.DepartmentEntity> departmentEntities = new ArrayList<>();
    public static final String tag = "ApplyPurchaseActivity";
    private String time;

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        editNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onPriceChange();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        editPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onPriceChange();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvUserName.setText(UserRequest.getInstance().getUser().getUser().getUName());
        tvNowDayTime.setText(TimeUtils.getNowNyr());
    }

    @Override
    protected void onRightTitleClick() {
        CommonToolHistoryActivity__JumpCenter
                .builder(this)
                .setNetToolType(3)
                .setToolType(ToolCode.TOOL_CG)
                .create().go();
    }

    /**
     * 价格变化
     */
    void onPriceChange(){
        try{
            int num = Integer.valueOf(editNum.getText().toString());
            double price = Double.valueOf(editPrice.getText().toString());
            tvMenoy.setText(String.valueOf(num*price));
        }catch (Exception e){
            tvMenoy.setText(String.valueOf(""));

        }


    }

    @OnClick(R.id.tv_up)
    void upData() {
        if (TextUtils.isEmpty(time)) {
            showToast("请输入时间");
            return;
        }
        String name = editName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            showToast("请输入物品名称");
            return;
        }
        if (TextUtils.isEmpty(editNum.getText().toString())) {
            showToast("请输入采购数量");
            return;
        }
        int num = Integer.valueOf(editNum.getText().toString());
        if (TextUtils.isEmpty(editPrice.getText().toString())) {
            showToast("请输入预估单价");
            return;
        }
        double price = Double.valueOf(editPrice.getText().toString());
        String context = editContent.getText();
        if (TextUtils.isEmpty(context)) {
            showToast("请输入采购事由");
            return;
        }
        if (sqrIds.size() == 0) {
            showToast("请选择审批人");
            return;
        }
        if (bmTypeId == NO_CHOSE) {
            showToast("请选择部门");
            return;
        }
        PurchaseDetailedCommitData jsonData = new PurchaseDetailedCommitData(name, num, price, time, bmTypeId, context);
        List<PurchaseDetailedCommitData> list = new ArrayList<>();
        list.add(jsonData);
        String json = new Gson().toJson(list);
        HttpHeper.get().toolService()
                .addPurchaseDetailed(sqrIds.toString(), json)
                .compose(bindToLifecycle())
                .compose(getThread())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(ApplyPurchaseActivity.this,data);
                        clearContent();
                    }
                });
    }

    /**
     * 部门
     */
    @OnClick(R.id.layoout_bumen)
    public void onLayoutChoseBmClicked() {
        if (departmentEntities.isEmpty()) {
            HttpHeper.get().toolService()
                    .getBuMen()
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<List<WplySqrandBmEntity.DepartmentEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(List<WplySqrandBmEntity.DepartmentEntity> data) {
                            departmentEntities.addAll(data);
                            showTypePicker();

                        }
                    });
        } else {
            showTypePicker();
        }
    }

    private void showTypePicker() {
        PickerViewProvider.getCommonPicker(this, departmentEntities, (options1, options2, options3, v) -> {
            tvBm.setText(departmentEntities.get(options1).getDName());
            bmTypeId = departmentEntities.get(options1).getDId();
        }).show();
    }

    @OnClick(R.id.layout_chose_time)
    public void onLayoutChoseStartTimeClicked() {
        PickerViewProvider.getDayTimePicker(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                time = TimeUtils.dateToStrM(date);
                tvTime.setText(time);
            }
        }).show();
    }


    @OnClick(R.id.layout_chose_spr)
    public void onLayoutChoseSprClicked() {
        if (peopleEntities.size() == 0) {
            HttpHeper.get().toolService().getCommonSpr(3)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<ArrayList<PeopleEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(ArrayList<PeopleEntity> data) {
                            peopleEntities.addAll(data);
                            ChosePeopleActivity__JumpCenter.builder(ApplyPurchaseActivity.this).setTag(tag).setData(peopleEntities).create().go();
                        }
                    });
        } else {
            ChosePeopleActivity__JumpCenter.builder(ApplyPurchaseActivity.this).setTag(tag).setData(peopleEntities).create().go();
        }
    }

    @Recipient(tag = tag + CHOSE_SPR_FINSH)
    void onChoseObjFinsh(int code, String info, List<PeopleEntity> peopleEntityList, List<Integer> checkIds) {
        tvSpr.setText(checkIds.size() == 0 ? "" : info);
        sqrIds.clear();
        sqrIds.addAll(checkIds);
        peopleEntities.clear();
        peopleEntities.addAll(peopleEntityList);
    }

    @Override
    protected void onDestroy() {
        RxEventProcessor.get().unBind(this);
        super.onDestroy();

    }
}
